<template>
	<view class="preview">
		<swiper circular :current="currentIndex" @change="swiperChange">
			<swiper-item v-for="item in classList" :key = "item._id">
				<image @click="maskChange" :src="item.picurl" mode="aspectFill"></image>
			</swiper-item>
			
			
		</swiper>
		<view class="mask" v-if="maskState">
			<!-- <view @click="safeBack" class="goBack" >
			    ← 返回
			  </view> -->
			
			<view class="count"  @click="safeBack">{{currentIndex + 1}}/{{classList.length}}</view>
			<view class="time">
				<uni-dateformat :date="new Date()" format="hh:mm" />
			</view>
			<view class="date">
				<uni-dateformat :date="new Date()" format="MM月dd日" />
			</view>
			<view class="footer">
				<view class="box" @click="clickInfo">
					<uni-icons type="info" size='28'></uni-icons>
					<view class="text">信息</view>
				</view><view class="box" @click="clickScore">
					<uni-icons type="star" size='28'></uni-icons>
					<view class="text">{{userScore}}分</view>
				</view>
				<view class="box" @click="clickDownLoad">
					<uni-icons type="download" size='24'></uni-icons>
					<view class="text">下载</view>
				</view>	
			</view>
		</view>
		<uni-popup ref="infoPopup" type="bottom">
			<view  class="infoPopup">
				<view class="popHeader">
					<view></view>
					<view class="title">壁纸信息</view>
					<view class="close" @click="clickInfoClose"><uni-icons type="closeempty" size="18" color="#999"></uni-icons></view>
				</view>
				<scroll-view scroll-y>
					<view class="content">
						<view class="row" >
							<view class="label">壁纸id</view>
							<text selectable class = 'value class'>{{currentInfo._id}}</text>
						</view>
						<view class="row" >
							<view class="label">分类</view>
							<text selectable class = 'value'>美女</text>
						</view>
						<view class="row" >
							<view class="label">发布者</view>
							<text selectable class = 'value'>{{currentInfo.nickname}}</text>
						</view>
						<view class="row" >
							<view class="label">评分</view>
							<uni-rate readonly touchable :value="userScore" size = '16'></uni-rate>
							<text selectable class = 'score'>{{userScore}}分</text>
						</view>
						<view class="row" >
							<view class="label">摘要</view>
							<text selectable class = 'value'>{{currentInfo.description}}</text>
						</view>
						<view class="row" >
							<view class="label">标签</view>
							<view class = 'value tabs'>
								<view class="tab" v-for = 'item in currentInfo.tabs'>
									{{item}}
								</view>
							</view>
						</view>
						<view class="copyright" >
							声明
							123456
						</view>
					</view>
				</scroll-view>
			</view>
			
		</uni-popup>
		<uni-popup ref="scorePopup" :is-mask-click="false">
			<view class="scorePopup">
				<view class="popHeader">
					<view></view>
					<view class="title">壁纸评分</view>
					<view class="close" @click="clickScoreClose"><uni-icons type="closeempty" size="18" color="#999"></uni-icons></view>
				</view>
				<view class="content">
					<uni-rate v-model="userScore" allowHalf></uni-rate>
					<text class= 'text'>{{userScore}} 分</text>
				</view>
				<view class="footer">
					<button @click="submitScore" :disabled="!userScore" type="default" size = 'mini' plain>确任评分</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import { ref } from 'vue';
	
	//import {getStatuBarHeight} from "@/utils/s"
	import {onLoad, onShareAppMessage, onShareTimeline} from "@dcloudio/uni-app"
	const maskState = ref(true)
	const infoPopup = ref(null)
	const scorePopup = ref(null)
	const userScore = ref(0)
	const classList = ref([])
	const currentId = ref(null)
	const currentIndex = ref(0)
	const currentInfo = ref(null);
	const maskChange = () =>{
		maskState.value = !maskState.value
	}
	
	const clickInfo  = () => {
		infoPopup.value.open();
	}
	
	const storgClassList = uni.getStorageSync('storgClassList') || [];
	classList.value = storgClassList.map(item => {
		return {
			...item, picurl:item.smallPicurl
		}
	})
	
	onLoad((e) => {
		currentId.value = e.id;
		currentIndex.value =  classList.value.findIndex(item=> item._id == currentId.value) 
		currentInfo.value = classList.value[currentIndex.value]
		console.log(currentIndex.value);
	})
	
	const swiperChange = (e) =>{
		currentIndex.value = e.detail.current;
		currentInfo.value = classList.value[currentIndex.value]
		console.log(e);
	}
	console.log(classList.value)
	function safeBack() {
	 
	    uni.switchTab({ url: '/pages/classify/classify' }); // 或者换成你的首页路径
	  
	}
	const idList = classList.value.map(item => ({
	  id: item._id,
	  classid: item.classid,
	  userScore: item.score,
	}))

	const clickInfoClose = () => {
		infoPopup.value.close();
	}
	
	const clickScore = () => {
		scorePopup.value.open();
	}
	
	const clickScoreClose= () => {
		scorePopup.value.close();
	}
	const submitScore = async () => {
	  const first = classList.value[0]
	  if (!first) {
	    uni.showToast({ title: '无数据', icon: 'none' })
	    return
	  }
	
	  // 提交评分
	  const res = await uni.request({
	    url: 'https://xrqr0h0x1w.gzg.sealos.run/setupScore',
	    method: 'POST',
	    data: {
	      id: first._id,
	      classid: first.classid,
	      score: userScore.value
	    },
	    header: {
	      'Content-Type': 'application/json'
	    }
	  })
	
	  if (res.statusCode === 200 && res.data.code === 200) {
	    uni.showToast({ title: '提交成功', icon: 'success' })
	
	    // 👇 提交成功后，调用添加 scoreSize 记录接口
	    await uni.request({
	      url: 'https://xrqr0h0x1w.gzg.sealos.run/add_scoredPic', // 改为你那个 add 接口路径
	      method: 'POST',
	      data: {
	        id: first._id,
	        classid: first.classid
	      },
	      header: {
	        'Content-Type': 'application/json'
	      },
	      success: (res2) => {
	        if (res2.data.code === 409) {
	          console.log('已存在，无需重复添加')
	        } else if (res2.data.code === 200) {
	          console.log('记录添加成功')
	        } else {
	          console.warn('记录添加失败', res2.data.message)
	        }
	      },
	      fail: (err) => {
	        console.error('记录添加请求失败', err)
	      }
	    })
	
	  } else {
	    uni.showToast({ title: res.data.message || '提交失败', icon: 'none' })
	  }
	}


	
const message = ref('')

const addDownloadSize = async () => {
  if (!currentInfo.value._id || !currentInfo.value.classid) {
    message.value = '缺少 _id 或 classid'
    return
  }

  try {
    const res = await uni.request({
      url: 'https://xrqr0h0x1w.gzg.sealos.run/add_downLoadPic', // 替换为你后端真实地址
      method: 'POST',
      data: {
        id: currentInfo.value._id,
        classid: currentInfo.value.classid
      },
      header: { 'Content-Type': 'application/json' }
    })

    if (res[1].data.code === 200) {
      message.value = '添加成功'
    } else if (res[1].data.code === 409) {
      message.value = '该项已存在'
    } else {
      message.value = res[1].data.message || '添加失败'
    }
  } catch (e) {
    message.value = '请求异常: ' + e.message
  }
}

	const clickDownLoad = () =>{
		// #ifdef H5
			uni.showModal({
				content:'请长按保存壁纸',
				showCancel:false
			})
		// #endif
		
		// #ifndef H5
		uni.showLoading({
			title:"下载中",
			mask:true
		})
		uni.getImageInfo({
		  src: currentInfo.value.picurl,
		  success: (res) => {
		    uni.saveImageToPhotosAlbum({
		      filePath: res.path,
		      success: (res) => {
		        //console.log(currentInfo.value);
				addDownloadSize();
		        uni.showToast({
		          title: "保存成功",
		          icon: "success"
		        });
		      },
		      fail: (err) => {
				  
				  return console.log(res);
				  if(err.errMsg == "saveImageToPhotosAlbum: fail cancel"){
					  uni.showToast({
					  	title:"保存失败，请重新下载",
						icon:"none"
					  })
					  return;
				  }
		        uni.showModal({
		          title: "提示",
		          content: "需要授权才可以下载图片呢",
		          success: (res) => {
		            if (res.confirm) {
		              uni.openSetting({
		                success(setting) {
		                  console.log(setting);
		                  if (setting.authSetting["scope.writePhotosAlbum"]) {
		                    uni.showToast({
		                      title: "可以下载照片咯",
		                      icon: "none"
		                    });
		                  } else {
		                    uni.showToast({
		                      title: "不能下载照片咯",
		                      icon: "none"
		                    });
		                  }
		                }
		              });
		            }
		          },
		          fail: () => {},
		          complete: () => {}
		        });
		      },
				  
			  complete:() => {
				  uni.hideLoading();
			  }
		    });
		  },
		  fail: (err) => {
		    console.error("获取图片信息失败:", err);
		    uni.showToast({
		      title: "图片加载失败",
		      icon: "none"
		    });
		  }
		});

		
		// #endif
	}
	onShareAppMessage(() =>{
			return{
				title:"天天de壁纸",
				
				path:"/pages/perview/perview?id="+currentId.value+"&type=share",
			}
	
	})
	
	//分享给朋友圈
	onShareTimeline(() => {
				 
			 return{
				 title:"天天de壁纸",
				 query:"id="+currentId.value+"&type=share",
				 //imageUrl:"https://cttxhy-1360132035.cos.ap-shanghai.myqcloud.com/ctt_logo/ctt_logo_1.jpg",
			 }
	})
</script>

<style scoped >
	.preview {
	  width: 100%;
	  height: 100vh;
	}
	
	/* swiper 和 image */
	.preview swiper {
	  width: 100%;
	  height: 100%;
	}
	
	.preview swiper image {
	  width: 100%;
	  height: 100%;
	}
	
	/* mask 及其子元素 */
	.preview .mask > view {
	  position: absolute;
	  left: 0;
	  right: 0;
	  margin: auto;
	  color: #ffffff;
	  width: fit-content;
	}
	
	.preview .mask .goBack {
	  position: absolute;
	  top: 0;
	  left: 0;
	}
	
	.preview .mask .count {
	  position: absolute;
	  top: 10vh;
	  background-color: rgba(0, 0, 0, 0.3);
	  font-size: 28rpx;
	  border-radius: 40rpx;
	  padding: 8rpx 28rpx;
	  backdrop-filter: blur(10rpx);
	}
	
	.preview .mask .time {
	  position: absolute;
	  font-size: 140rpx;
	  top: calc(10vh + 80rpx);
	  font-weight: 100;
	  line-height: 1em;
	  text-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
	}
	
	.preview .mask .date {
	  position: absolute;
	  font-size: 34rpx;
	  top: calc(10vh + 230rpx);
	  text-shadow: 0 2rpx rgba(0, 0, 0, 0.3);
	}
	
	.preview .mask .footer {
	  position: absolute;
	  background: rgba(255, 255, 255, 0.8);
	  bottom: 10vh;
	  width: 65vw;
	  height: 120rpx;
	  border-radius: 120rpx;
	  color: #000000;
	  display: flex;
	  justify-content: space-around;
	  align-items: center;
	  box-shadow: 0 2rpx 0 rgba(0, 0, 0, 0.1);
	  backdrop-filter: blur(20rpx);
	}
	
	.preview .mask .footer .box {
	  display: flex;
	  flex-direction: column;
	  align-items: center;
	  justify-content: center;
	  padding: 2rpx 12rpx;
	}
	
	.preview .mask .footer .box .text {
	  font-size: 26rpx;
	  color: #777777;
	}
	
	/* popHeader */
	.preview .popHeader {
	  display: flex;
	  justify-content: space-between;
	  align-items: center;
	}
	
	.preview .popHeader .title {
	  color: #666666; /* 这里原来是 $text-font-color-2，换成灰色 */
	  font-size: 26rpx;
	}
	
	.preview .popHeader .close {
	  border: 1px solid red;
	  padding: 6rpx;
	}
	
	/* infoPopup */
	.preview .infoPopup {
	  background: white;
	  padding: 30rpx;
	  border-radius: 30rpx 30rpx 0 0;
	  overflow: hidden;
	}
	
	.preview .infoPopup scroll-view {
	  max-height: 60vh;
	}
	
	.preview .infoPopup .content .row {
	  display: flex;
	  padding: 16rpx 0;
	  font-size: 32rpx;
	  line-height: 1.7em;
	}
	
	.preview .infoPopup .content .row .label {
	  color: #a7a7a7;
	  width: 140rpx;
	  text-align: right;
	  font-size: 30rpx;
	}
	
	.preview .infoPopup .content .row .value {
	  flex: 1;
	  width: 0;
	}
	
	.preview .infoPopup .content .row .roteBox {
	  display: flex;
	  align-items: center;
	}
	
	.preview .infoPopup .content .row .roteBox .score {
	  font-size: 26rpx;
	  color: #a7a7a7;
	  padding-left: 10rpx;
	}
	
	.preview .infoPopup .content .row .tabs {
	  display: flex;
	  flex-wrap: wrap;
	}
	
	.preview .infoPopup .content .row .tabs .tab {
	  border: 1px solid;
	  color: #a7a7a7;
	  padding: 10rpx 30rpx;
	  border-radius: 40rpx;
	  line-height: 1em;
	  margin: 0 10rpx 10rpx 0;
	}
	
	/* copyright */
	.preview .infoPopup .content .copyright {
	  font-size: 28rpx;
	  padding: 20rpx;
	  background: #F6F6F6;
	  color: #666666;
	  border-radius: 10rpx;
	  margin: 20rpx 0;
	  line-height: 1.6em;
	}
	
	/* scorePopup */
	.preview .scorePopup {
	  background: #fff;
	  padding: 30rpx;
	  width: 70vw;
	  border-radius: 30rpx;
	}
	
	.preview .scorePopup .content {
	  padding: 30rpx 0;
	  display: flex;
	  justify-content: center;
	  align-items: center;
	}
	
	.preview .scorePopup .content .text {
	  color: #FFCA3E;
	  padding-left: 10rpx;
	  width: 80rpx;
	  line-height: 1em;
	  text-align: right;
	}
	
	.preview .scorePopup .footer {
	  padding: 10rpx 0;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	}

</style>
